package com.woniuxy.joylifeforum.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniuxy.common.entity.*;
import com.woniuxy.common.mapper.*;
import com.woniuxy.common.utils.KeyUtil;
import com.woniuxy.joylifeforum.controller.ChatWebSocketController;
import com.woniuxy.joylifeforum.controller.MyController;
import com.woniuxy.joylifeforum.dto.UserMes;
import com.woniuxy.joylifeforum.service.NewsService;
import com.woniuxy.joylifeforum.utils.ForumRedis;
import com.woniuxy.joylifeforum.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.websocket.RemoteEndpoint;
import javax.websocket.Session;
import java.io.IOException;
import java.util.*;

@Service
public class NewsServiceImpl implements NewsService {
    @Autowired
    private ForumTopicMapper forumTopicMapper;
    @Autowired
    private ForumReplyMapper forumReplyMapper;
    @Autowired
    private CenterUserMapper centerUserMapper;
    @Autowired
    private ForumForumMapper forumForumMapper;
    @Autowired
    private ForumConcernMapper forumConcernMapper;
    @Autowired
    private ForumTopicPraiseMapper forumTopicPraiseMapper;
    @Autowired
    private ForumRedis forumRedis;
    @Autowired
    private ForumPhotoMapper forumPhotoMapper;
    @Autowired
    private ForumTopicCollectMapper forumTopicCollectMapper;
    @Autowired
    private ForumExpMapper forumExpMapper;
    @Autowired
    private ForumReplyPraiseMapper ForumReplyPraiseMapper;
    @Autowired
    private ForumTopicReportMapper forumTopicReportMapper;
    @Autowired
    private ForumReplyReportMapper forumReplyReportMapper;
    @Autowired
    private ForumAdminMapper forumAdminMapper;
    @Autowired
    private ForumFansMapper forumFansMapper;
    @Autowired
    private ForumContactsMapper forumContactsMapper;
    @Autowired
    private ForumMessageMapper forumMessageMapper;
    @Autowired
    private RedisUtil redisUtil;
    /*
    查询用户通知
     */
    @Override
    @Transactional
    public List<UserMes> findRemindService(String userId) {
        //查询未读话题赞
        ForumTopicPraiseExample topicPraiseExample = new ForumTopicPraiseExample();
        ForumTopicPraiseExample.Criteria criteria1 = topicPraiseExample.createCriteria();
        criteria1.andIsReadEqualTo(1);
        criteria1.andIsReadEqualTo(1);
        long TopicNum = forumTopicPraiseMapper.countByExample(topicPraiseExample);

        ForumTopicPraiseExample topicPraise1 = new ForumTopicPraiseExample();
        topicPraise1.setOrderByClause("date DESC");
        ForumTopicPraiseExample.Criteria criteria = topicPraise1.createCriteria();
        criteria.andReceiveIdEqualTo(userId);
        if (TopicNum < 10) {
            //至少查询10条信息
            PageHelper.startPage(1, 10);
        }else {
            criteria.andIsReadEqualTo(1);
        }
        List<ForumTopicPraise> forumTopicPraises = forumTopicPraiseMapper.selectByExample(topicPraise1);
        //查询回复赞
        ForumReplyPraiseExample replyPraise1 = new ForumReplyPraiseExample();
        ForumReplyPraiseExample.Criteria criteria3 = replyPraise1.createCriteria();
        criteria3.andReceiveIdEqualTo(userId);
        criteria3.andIsReadEqualTo(1);
        long replyNum = ForumReplyPraiseMapper.countByExample(replyPraise1);

        ForumReplyPraiseExample replyPraise = new ForumReplyPraiseExample();
        replyPraise.setOrderByClause("date DESC");
        ForumReplyPraiseExample.Criteria criteria4 = replyPraise.createCriteria();
        criteria4.andReceiveIdEqualTo(userId);
        if (replyNum < 10) {
            //至少查询10条信息
            PageHelper.startPage(1, 10);
        }else{
            criteria4.andIsReadEqualTo(1);
        }
        List<ForumReplyPraise> forumReplyPraises = ForumReplyPraiseMapper.selectByExample(replyPraise);
        //赋值
        List<UserMes>userMes=new ArrayList<>();
        //话题赋值
        for (ForumTopicPraise forumTopicPraise:forumTopicPraises){
            String topicId = forumTopicPraise.getTopicId();
            String content = forumTopicMapper.selectByPrimaryKey(topicId).getContent();
            Integer type=1;
            Integer isRead=forumTopicPraise.getIsRead();
            Date date = forumTopicPraise.getDate();
            CenterUser centerUser = centerUserMapper.selectByPrimaryKey(forumTopicPraise.getUserId());
            userMes.add(new UserMes(topicId,content,type,isRead,date,centerUser));
            //已读状态更改
            ForumTopicPraise forumTopicPraise1 = forumTopicPraiseMapper.selectByPrimaryKey(forumTopicPraise.getId());
            forumTopicPraise1.setIsRead(0);
            forumTopicPraiseMapper.updateByPrimaryKey(forumTopicPraise1);
        }
        //回复赋值
        for (ForumReplyPraise forumReplyPraise:forumReplyPraises){
            ForumReply forumReply = forumReplyMapper.selectByPrimaryKey(forumReplyPraise.getReplyId());
            String topicId1 = forumReply.getTopicId();
            String content1 = forumReply.getContent();
            Integer type1=0;
            Integer isRead1=forumReplyPraise.getIsRead();
            Date date1 = forumReplyPraise.getDate();
            CenterUser centerUser = centerUserMapper.selectByPrimaryKey(forumReplyPraise.getUserId());
            userMes.add(new UserMes(topicId1,content1,type1,isRead1,date1,centerUser));
            //已读状态更改
            ForumReplyPraise forumReplyPraise1 = ForumReplyPraiseMapper.selectByPrimaryKey(forumReplyPraise.getId());
            forumReplyPraise1.setIsRead(0);
            ForumReplyPraiseMapper.updateByPrimaryKey(forumReplyPraise1);
        }
        Collections.sort(userMes,(o1, o2) -> {
            if(o1.getDate().after(o2.getDate())){
                return -1;
            }else{
                return 1;
            }
        });
        return userMes;
    }
    /*
    回复提醒
     */
    @Override
    public PageInfo<Map<String,Object>> findReplyRemindService(Integer page, Integer limit, String userId) {
        //检索出回复
        ForumReplyExample replyExample=new ForumReplyExample();
        replyExample.setOrderByClause("date DESC");
        replyExample.createCriteria().andReplyUserIdEqualTo(userId);
        PageHelper.startPage(page,limit);
        List<ForumReply> forumReplies = forumReplyMapper.selectByExampleWithBLOBs(replyExample);
        //遍历赋值
        List< Map<String,Object>>data=new ArrayList<>();
        for(ForumReply forumReply:forumReplies){
            //回复用户
            CenterUser centerUser = centerUserMapper.selectByPrimaryKey(forumReply.getUserId());
            //我的内容
            String content;
            if(forumReply.getReplyId()==null){
                //获取话题内容
                content = forumTopicMapper.selectByPrimaryKey(forumReply.getTopicId()).getContent();
            }else{
                //获取回复内容
                content = forumReplyMapper.selectByPrimaryKey(forumReply.getReplyId()).getContent();
            }
            //社区赋值
            ForumForum forumForum = forumForumMapper.selectByPrimaryKey(forumReply.getForumId());
            //已读赋值
            if(forumReply.getIsRead()==1){
                //赋值0
                forumReply.setIsRead(0);
                forumReplyMapper.updateByPrimaryKey(forumReply);
            }
            //保存
            Map<String,Object>map =new HashMap<>();
            map.put("forumReply",forumReply);
            map.put("centerUser",centerUser);
            map.put("content",content);
            map.put("forumForum",forumForum);
            data.add(map);
        }
        PageInfo<Map<String,Object>> dataHP=new PageInfo<>(data);
        return dataHP;
    }
    /*
    获取用户关注
     */
    @Override
    public List<CenterUser> userContent(String userId) {
        //获取关注的人
        ForumFansExample fansExample=new ForumFansExample();
        fansExample.createCriteria().andFansIdEqualTo(userId);
        List<ForumFans> forumFans = forumFansMapper.selectByExample(fansExample);
        //用户集合赋值
        List<CenterUser>users=new ArrayList<>();
        for(ForumFans fans:forumFans) {
            CenterUser centerUser = centerUserMapper.selectByPrimaryKey(fans.getUserId());
            users.add(centerUser);
        }
        return users;
    }
    /*
    最近联系人
     */
    @Override
    public List<Map<String, Object>> findLatelyUser(String userId) {
        //检索最近联系人
        ForumContactsExample contacts=new ForumContactsExample();
        contacts.createCriteria().andUserIdEqualTo(userId);
        List<ForumContacts> forumContacts = forumContactsMapper.selectByExample(contacts);
        //联系人赋值
        List<Map<String,Object>>data=new ArrayList<>();
        for(ForumContacts contact:forumContacts){
            //人赋值
            CenterUser centerUser = centerUserMapper.selectByPrimaryKey(contact.getContactsId());
            //最新消息查询
            ForumMessage forumMessage = forumMessageMapper.selectByPrimaryKey(contact.getMessageId());
            //保存
            Map<String,Object>map=new HashMap<>();
            map.put("centerUser",centerUser);
            map.put("forumMessage",forumMessage);
            data.add(map);
        }
        //排序
        Collections.sort(data,(o1, o2) -> {
            if(((ForumMessage)(o1.get("forumMessage"))).getDate().after(((ForumMessage)(o2.get("forumMessage"))).getDate())){
                return -1;
            }else{
                return 1;
            }
        });
        return data;
    }
    /*
    聊天记录
     */
    @Override
    @Transactional
    public Map<String, Object> findChatting(Integer page, Integer limit, String userId, String oppositeUserId) {
        PageHelper.startPage(page,limit);
        List<ForumMessage> record = forumMessageMapper.findRecord(userId, oppositeUserId);
        //状态该已读
        for (ForumMessage forumMessage:record){
            if(forumMessage.getStatus()==1&&forumMessage.getUserId().equals(oppositeUserId)){
                forumMessage.setStatus(0);
                forumMessageMapper.updateByPrimaryKey(forumMessage);
            }
        }
        PageInfo<ForumMessage>recordPH=new PageInfo<>(record);
        //好友赋值
        CenterUser oppositeUser = centerUserMapper.selectByPrimaryKey(oppositeUserId);
        //自己赋值
        CenterUser user = centerUserMapper.selectByPrimaryKey(userId);
        //保存
        Map<String,Object>data=new HashMap<>();
        data.put("recordPH",recordPH);
        data.put("oppositeUser",oppositeUser);
        data.put("user",user);
        return data;
    }
    /*
    聊天提交
     */
    @Override
    @Transactional
    public int submitChatService(String userId, String oppositeUserId, String mes) {
        //聊天信息id
        String id = UUID.randomUUID().toString();
        //websocket推送，暂时websocket回调无法写数据库，暂时屏蔽，改用验证session是否存在判断已读
        Session session = ChatWebSocketController.sessions.get(oppositeUserId+"-"+userId);
       // System.out.println("session-"+session);
        //Session session = (Session) redisUtil.get(oppositeUserId);
        if(session!=null){
            final RemoteEndpoint.Basic basic = session.getBasicRemote();
            if(basic!=null){
                try {
                    String uuid = KeyUtil.generateKey();
                    basic.sendText(uuid+"-"+mes);
                    //添加redis缓存
                    redisUtil.set(uuid,id,30);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //判断用户是否已读
        Integer isRead=1;
        if(session!=null){
            isRead=0;
        }
        //聊天提交
        ForumMessage message=new ForumMessage(id,userId,oppositeUserId,new Date(),isRead,mes);
        forumMessageMapper.insert(message);
        //最近我的联系人判断
        ForumContactsExample contacts1=new ForumContactsExample();
        ForumContactsExample.Criteria criteria = contacts1.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andContactsIdEqualTo(oppositeUserId);
        List<ForumContacts> forumContacts = forumContactsMapper.selectByExample(contacts1);
        if(forumContacts.size()==0){
            //创建最近联系人
            String id1 = KeyUtil.generateKey();
            ForumContacts contactsEntity=new ForumContacts(id1,userId,oppositeUserId,id);
            forumContactsMapper.insert(contactsEntity);
        }else{
            //修改最新消息
            forumContacts.get(0).setMessageId(id);
            forumContactsMapper.updateByPrimaryKey(forumContacts.get(0));
        }
        //对方联系人判断
        ForumContactsExample contacts2=new ForumContactsExample();
        ForumContactsExample.Criteria criteria1 = contacts2.createCriteria();
        criteria1.andUserIdEqualTo(oppositeUserId);
        criteria1.andContactsIdEqualTo(userId);
        List<ForumContacts> forumContacts1 = forumContactsMapper.selectByExample(contacts2);
        if(forumContacts1.size()==0){
            //创建对方最近联系人
            String id2 = KeyUtil.generateKey();
            ForumContacts contactsEntity2=new ForumContacts(id2,oppositeUserId,userId,id);
            forumContactsMapper.insert(contactsEntity2);
        }else{
            //修改最新消息
            forumContacts1.get(0).setMessageId(id);
            forumContactsMapper.updateByPrimaryKey(forumContacts1.get(0));
        }

        return 1;
    }
    /*
    获取用户粉丝
     */
    @Override
    public List<Map<String, Object>> userFans(String userId, String findUserId) {
        //获取粉丝
        ForumFansExample fansExample=new ForumFansExample();
        fansExample.createCriteria().andUserIdEqualTo(findUserId);
        List<ForumFans> forumFans = forumFansMapper.selectByExample(fansExample);
        //用户集合赋值
        List<Map<String,Object>>users=new ArrayList<>();
        for(ForumFans fans:forumFans) {
            //用户赋值
            CenterUser userFans = centerUserMapper.selectByPrimaryKey(fans.getFansId());
            //判断关注情况
            ForumFansExample fansCount=new ForumFansExample();
            ForumFansExample.Criteria criteria = fansCount.createCriteria();
            criteria.andUserIdEqualTo(fans.getFansId());
            criteria.andFansIdEqualTo(userId);
            long status = forumFansMapper.countByExample(fansCount);
            Map<String,Object>map=new HashMap<>();
            map.put("userFans",userFans);
            map.put("status",status);
            users.add(map);
        }
        return users;
    }
    //标记已读,暂时websocket回调无法写数据库，暂时屏蔽，改用验证session是否存在判断已读
    @Override
    public void isread(String charId) {
        ForumMessageMapper forumMessageMapper = (ForumMessageMapper) ChatWebSocketController.applicationContext.getBean("forumMessageMapper");
        System.out.println("charid="+charId);
        forumMessageMapper.isRead(charId);
        //ForumMessage forumMessage = forumMessageMapper.selectByPrimaryKey(charId);
        //System.out.println(forumMessage);
    }
}
